package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.management.aop.anno.Cacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author: byLengs
 * @Date: 2025/10/18 11:09
 * @Description:
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class CacheableAspect {

    @Autowired
    private StringRedisTemplate redisClient;

    @Pointcut("@annotation(com.qk.management.aop.anno.Cacheable)")
    public void pt() {
    }

    @Around("pt()")
    public Object cacheable(ProceedingJoinPoint pjp) {
        Object resultValue = null;
        String redisKey = "";
        long expireTime = 0L;
        TimeUnit timeUnit = TimeUnit.MINUTES;
        try {
            Class<?> targetClass = pjp.getTarget().getClass();
            String methodName = pjp.getSignature().getName();
            Method method = targetClass.getMethod(methodName);
            Cacheable annotation = method.getAnnotation(Cacheable.class);
            expireTime = annotation.expireTime();
            timeUnit = annotation.timeUnit();
            redisKey = annotation.keyPrefix() + methodName;
            String jsonStr = redisClient.opsForValue().get(redisKey);

            if (ObjectUtil.isNotEmpty(jsonStr)) {
                return JSONUtil.toBean(redisClient.opsForValue().get(redisKey), method.getReturnType());
            }
        } catch (Throwable e) {
            log.error("查询缓存失败:{}" + e.getMessage());
        }
        try {
            resultValue = pjp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException("您的操作有误,请稍后重试!", e);
        }
        try {
            redisClient.opsForValue().set(redisKey, JSONUtil.toJsonStr(resultValue), expireTime, timeUnit);
        } catch (Exception e) {
            log.error("添加缓存失败", e);
        }
        return resultValue;
    }
}
